package com.laihuichuxing.order.concurrent;

import java.util.LinkedList;
 /**
  * Description: 任务队列
  * Author: Qinxuefeng
  * Version: 1.0
  * Create Date Time: 2018/10/15 17:27.
  * Update Date Time:
  */
public class LinkeRunnableQueue implements RunnableQueue{

	//任务队列的最大容量
	private final int limit;

	//若任务队列的任务已经满了，则需要执行拒绝策略
	private final DenyPolicy denyPolicy;

	//存放任务队列
	private final LinkedList<Runnable> runnableList = new LinkedList<>();

	private final ThreadPool threadPool;
	public LinkeRunnableQueue(int limit,DenyPolicy denyPolicy,ThreadPool threadPool) {
		this.limit=limit;
		this.denyPolicy=denyPolicy;
		this.threadPool=threadPool;

	}
	@Override
	public void offer(Runnable runnable) {

		synchronized(runnableList) {
			if(runnableList.size()>=limit) {
				//无法容纳新的任务时执行拒绝策略
				denyPolicy.reject(runnable, threadPool);
			}else {
				//将任务加入队列队尾，并且唤醒阻塞的线程
				runnableList.addLast(runnable);
				runnableList.notifyAll();
			}
		}
	}

	@Override
	public Runnable take() throws InterruptedException {
		synchronized(runnableList) {
			while(runnableList.isEmpty()) {
				try {
					runnableList.wait();
				} catch (InterruptedException e) {
					throw e;
				}
			}
			return runnableList.removeFirst();
		}
	}

	@Override
	public int size() {
		synchronized(runnableList) {
			return runnableList.size();
		}
	}


}
